import Vue from 'vue'
import Router from 'vue-router'
import { isURL } from '@/utils/validate'
import { asyncRoutes, constantRoutes } from './config'

Vue.use(Router)

// 解决导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})


export function generateAsyncRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
      continue
    }
    // 组装路由
    var route = {
      path: '',
      component: null,
      name: '',
      hidden: menuList[i].hidden,
      meta: {
        name: '',        // 名称, 由 this.$route.name 自动赋值（默认，名称 === 路由名称 === 路由路径）
        params: {},      // 参数, 由 this.$route.params 自动赋值
        query: {},       // 查询参数, 由 this.$route.query 自动赋值
        menuId: menuList[i].id,
        title: menuList[i].name,
        iframeURL: ''    // 是否通过iframe嵌套展示内容? (以http[s]://开头, 自动匹配)
      }
    }
    // eslint-disable-next-line
    let URL = (menuList[i].url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      route['path'] = URL
      route['name'] = `i-${ menuList[i].id }`
      route['meta']['iframeURL'] = URL
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-')
      route['path'] = URL
      route['name'] = URL.replace(/\//g, '-')
      route['component'] = () => import(`@/views/modules/${ URL }`)
    }
    routes.push(route)
  }
  if (temp.length >= 1) {
    generateAsyncRoutes(temp, routes)
  }

  // 组装主路由
  let mainRouter = [
    {
      path: '/',
      component: () => import('@/views/main'),
      name: 'main',
      redirect: { name: 'home' },
      meta: { title: '主入口布局' },
      children: [
        { path: '/home', component: () => import('@/views/modules/home'), name: 'home', meta: { title: '首页' } }
      ].concat(routes),
    },
    {
      path: '*', redirect: '/404', hidden: true
    }
  ]

  return mainRouter.concat();
}
